const mysql = require('mysql2/promise');

// 测试数据库连接
async function testDatabaseConnection() {
  try {
    // 从环境变量或配置中获取数据库信息
    const pool = mysql.createPool({
      host: process.env.DB_HOST || 'localhost',
      user: process.env.DB_USER || 'root',
      password: process.env.DB_PASSWORD || '',
      database: process.env.DB_NAME || 'xlcig',
      waitForConnections: true,
      connectionLimit: 10,
      queueLimit: 0
    });

    console.log('🔌 正在测试数据库连接...');

    // 测试连接
    const connection = await pool.getConnection();
    console.log('✅ 数据库连接成功');
    
    // 检查ai_chat_records表是否存在
    const [tables] = await connection.execute("SHOW TABLES LIKE 'ai_chat_records'");
    if (tables.length === 0) {
      console.log('❌ ai_chat_records表不存在，正在创建...');
      
      // 创建表
      await connection.execute(`
        CREATE TABLE ai_chat_records (
          id INT PRIMARY KEY AUTO_INCREMENT,
          user_id INT NOT NULL,
          session_id VARCHAR(255) NOT NULL,
          message_type ENUM('user', 'assistant') NOT NULL,
          content TEXT NOT NULL,
          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          INDEX idx_user_session (user_id, session_id),
          INDEX idx_created_at (created_at)
        )
      `);
      
      console.log('✅ ai_chat_records表创建成功');
    } else {
      console.log('✅ ai_chat_records表存在');
    }

    // 检查表结构
    const [columns] = await connection.execute("DESCRIBE ai_chat_records");
    console.log('📋 表结构:');
    columns.forEach(col => {
      console.log(`  - ${col.Field}: ${col.Type} ${col.Null === 'NO' ? 'NOT NULL' : ''} ${col.Key ? `(${col.Key})` : ''}`);
    });

    // 检查最近的记录
    const [recentRecords] = await connection.execute(
      "SELECT id, user_id, session_id, message_type, SUBSTRING(content, 1, 50) as content_preview, created_at FROM ai_chat_records ORDER BY created_at DESC LIMIT 5"
    );
    
    console.log(`📊 最近${recentRecords.length}条记录:`);
    recentRecords.forEach(record => {
      console.log(`  ID:${record.id} 用户:${record.user_id} 类型:${record.message_type} 时间:${record.created_at}`);
      console.log(`    内容预览: ${record.content_preview}...`);
    });

    // 测试插入
    console.log('🧪 测试插入数据...');
    const testSessionId = `test-${Date.now()}`;
    await connection.execute(
      "INSERT INTO ai_chat_records (user_id, session_id, message_type, content) VALUES (?, ?, ?, ?)",
      [999, testSessionId, 'user', '测试消息']
    );
    
    await connection.execute(
      "INSERT INTO ai_chat_records (user_id, session_id, message_type, content) VALUES (?, ?, ?, ?)",
      [999, testSessionId, 'assistant', '测试AI回复']
    );
    
    console.log('✅ 测试数据插入成功');

    // 清理测试数据
    await connection.execute(
      "DELETE FROM ai_chat_records WHERE session_id = ?",
      [testSessionId]
    );
    
    console.log('🧹 测试数据清理完成');

    connection.release();
    await pool.end();
    
    console.log('🎉 数据库测试完成，一切正常！');
    
  } catch (error) {
    console.error('❌ 数据库测试失败:', error);
    process.exit(1);
  }
}

// 运行测试
testDatabaseConnection(); 